//----------------------------------Include-------------------------------------
#include "mcu.h"
//------------------------------------------------------------------------------

//-----------------------------------Macro--------------------------------------
#define _SPI_INST      SPI3
//------------------------------------------------------------------------------

//--------------------------------Static Var------------------------------------
//------------------------------------------------------------------------------

//--------------------------------Public Func-----------------------------------
void mcu_init_spi3(void)
{
//pin
  RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOB, ENABLE);
  
  //PB6 - CS    PB3 - SCLK    PB4 - MISO    PB5 - MOSI
  GPIO_InitType     GPIO_InitS;
  GPIO_InitStruct (&GPIO_InitS);
  
  //SCLK/MOSI
  GPIO_InitS.Pin            = GPIO_PIN_3 | GPIO_PIN_5;
  GPIO_InitS.GPIO_Speed     = GPIO_Speed_2MHz;
  GPIO_InitS.GPIO_Mode      = GPIO_Mode_AF_PP;
  GPIO_InitPeripheral(GPIOB, &GPIO_InitS);
  //MISO
  GPIO_InitS.Pin            = GPIO_PIN_4;
  GPIO_InitS.GPIO_Mode      = GPIO_Mode_IN_FLOATING;
  GPIO_InitPeripheral(GPIOB, &GPIO_InitS);
  //CS
  GPIO_InitS.Pin            = GPIO_PIN_6;
  GPIO_InitS.GPIO_Mode      = GPIO_Mode_Out_PP;
  GPIO_InitPeripheral(GPIOB, &GPIO_InitS);
  GPIO_SetBits(GPIOB, GPIO_PIN_6);
  
//spi
  RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_SPI3, ENABLE);

  SPI_InitType    SPI_InitS;
  SPI_InitStruct(&SPI_InitS);
  
  SPI_InitS.DataDirection = SPI_DIR_DOUBLELINE_FULLDUPLEX;
  SPI_InitS.SpiMode       = SPI_MODE_MASTER;
  SPI_InitS.DataLen       = SPI_DATA_SIZE_8BITS;
  SPI_InitS.CLKPOL        = SPI_CLKPOL_LOW;
  SPI_InitS.CLKPHA        = SPI_CLKPHA_FIRST_EDGE;
  SPI_InitS.NSS           = SPI_NSS_SOFT;
  SPI_InitS.BaudRatePres  = SPI_BR_PRESCALER_4;
  SPI_InitS.FirstBit      = SPI_FB_MSB;
  SPI_InitS.CRCPoly       = 7;
  SPI_Init(_SPI_INST, &SPI_InitS);
  
  SPI_Enable(_SPI_INST, ENABLE);
}

//CS
void mcu_spi3_cs(uint8_t level)
{
  level ? GPIO_SetBits(GPIOB, GPIO_PIN_6) : GPIO_ResetBits(GPIOB, GPIO_PIN_6);
}

//read write
uint8_t mcu_spi3_rdwr_byte(uint8_t TxData)
{
  static uint32_t retry=0;
  while( !(_SPI_INST->STS & (1<<1)) ){ //[1]TE  0:TX 缓存器非空 1:TX 缓存器为空
    retry++;
    if(retry>1000) return 0;
  }
  
  _SPI_INST->DAT = TxData;
  
  retry=0;
  while( !(_SPI_INST->STS & (1<<0)) ){ //[0]RNE 接收缓存器非空标志位  0:RX 缓存器为空  1:RX 缓存器非空
    retry++;
    if(retry>1000) return 0;           //根据实际情况调整
  }
  
  return _SPI_INST->DAT;
}
//------------------------------------EOF---------------------------------------

